﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Com.Alipay;
using Model;
using System.Data;

namespace SuuntoWebsite.Events._201205
{
    public partial class Success : System.Web.UI.Page
    {
        protected static string sqlCon = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString_Event"].ConnectionString;
        protected static string emailHost = System.Configuration.ConfigurationManager.AppSettings["emailHost"];
        protected static string emailAccount = System.Configuration.ConfigurationManager.AppSettings["emailAccount"];
        protected static string emailPwd = System.Configuration.ConfigurationManager.AppSettings["emailPwd"];
        protected static string emailFrom = System.Configuration.ConfigurationManager.AppSettings["emailFrom"];
        protected string rewrite = System.Configuration.ConfigurationManager.AppSettings["rewriteType"];
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Public.Cookie.UserId.Equals("0"))
                Response.Redirect("./registration" + rewrite);


            SortedDictionary<string, string> sPara = GetRequestGet();

            if (sPara.Count > 0)//判断是否有带返回参数
            {
                InsertLog(sPara);
                Notify aliNotify = new Notify();
                bool verifyResult = aliNotify.Verify(sPara, Request.QueryString["notify_id"], Request.QueryString["sign"]);

                if (verifyResult)//验证成功
                {
                    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
                    //请在这里加上商户的业务逻辑程序代码

                    //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
                    //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表
                    string trade_no = Request.QueryString["trade_no"];              //支付宝交易号
                    string order_no = Request.QueryString["out_trade_no"];	        //获取订单号
                    string total_fee = Request.QueryString["price"];	            //获取总金额
                    string subject = Request.QueryString["subject"];                //商品名称、订单名称
                    string body = Request.QueryString["body"];                      //商品描述、订单备注、描述
                    string buyer_email = Request.QueryString["buyer_email"];        //买家支付宝账号
                    string receive_name = Request.QueryString["receive_name"];      //收货人姓名
                    string receive_address = Request.QueryString["receive_address"];//收货人地址
                    string receive_zip = Request.QueryString["receive_zip"];        //收货人邮编
                    string receive_phone = Request.QueryString["receive_phone"];    //收货人电话
                    string receive_mobile = Request.QueryString["receive_mobile"];  //收货人手机
                    string trade_status = Request.QueryString["trade_status"];      //交易状态

                    if (Request.QueryString["trade_status"] == "WAIT_SELLER_SEND_GOODS")
                    {
                        //判断该笔订单是否在商户网站中已经做过处理（可参考“集成教程”中“3.4返回数据处理”）
                        //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                        //如果有做过处理，不执行商户的业务程序
                        bool flag = new Bll.EventForSuunto.BLLSuunto_Order().SuuntoOrderUpdate(sqlCon, order_no,
                                                                                               "买家以付款，等待卖家发货",
                                                                                               DateTime.Now);
                        if (flag)
                        {
                            DataTable dt = new Bll.EventForSuunto.BLLSuunto_Order().SuuntoOrderByPKID(sqlCon, order_no);
                            if(dt.Rows.Count>0)
                            {
                                OrderInfo.DataSource = dt;
                                OrderInfo.DataBind();
                                DataTable emailDt = new Bll.EventForSuunto.DALSuunto_Email().GetEmailConfig(sqlCon);
                                Public.SendEmail.Sendmail(emailDt, dt.Rows[0]["S_Email"].ToString(), "验证码",
                                                          dt.Rows[0]["O_Code"].ToString());
                                dt.Dispose();
                                Public.Cookie.UserId = "0";
                                Public.Cookie.UserName = "0";
                                Public.Cookie.StoreId = "0";
                                Public.Cookie.ProductId = "0";
                            }
                        }
                        else
                        {
                            Response.Write("error");
                        }
                    }
                    else
                    {
                        Response.Write("trade_status=" + Request.QueryString["trade_status"]);
                    }

                    //打印页面
                    //Response.Write("验证成功<br />");
                    //Response.Write("trade_no=" + trade_no);

                    //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——

                    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
                }
                else//验证失败
                {
                    Response.Write("验证失败");
                }
            }
            else
            {
                Response.Write("无返回参数");
            }
        }
        /// <summary>
        /// 获取支付宝GET过来通知消息，并以“参数名=参数值”的形式组成数组
        /// </summary>
        /// <returns>request回来的信息组成的数组</returns>
        public SortedDictionary<string, string> GetRequestGet()
        {
            int i = 0;
            SortedDictionary<string, string> sArray = new SortedDictionary<string, string>();
            NameValueCollection coll;
            //Load Form variables into NameValueCollection variable.
            coll = Request.QueryString;

            // Get names of all forms into a string array.
            String[] requestItem = coll.AllKeys;

            for (i = 0; i < requestItem.Length; i++)
            {
                sArray.Add(requestItem[i], Request.QueryString[requestItem[i]]);
            }

            return sArray;
        }
        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="par">支付宝返回实体</param>
        public void InsertLog(SortedDictionary<string, string> par)
        {
            ModelEvent.ModelSuunto_Paylog model = new ModelEvent.ModelSuunto_Paylog();
            model.buyer_email = par["buyer_email"];
            model.buyer_id = par["buyer_id"];
            model.discount = par["discount"];
            model.gmt_create = par["gmt_create"];
            model.gmt_logistics_modify = par["gmt_logistics_modify"];
            model.gmt_payment = par["gmt_payment"];
            model.is_success = par["is_success"];
            model.is_total_fee_adjust = par["is_total_fee_adjust"];
            model.logistics_fee = par["logistics_fee"];
            model.logistics_payment = par["logistics_payment"];
            model.logistics_type = par["logistics_type"];
            model.notify_id = par["notify_id"];
            model.notify_time = par["notify_time"];
            model.notify_type = par["notify_type"];
            model.out_trade_no = par["out_trade_no"];
            model.payment_type = par["payment_type"];
            model.price = par["price"];
            model.quantity = par["quantity"];
            model.receive_address = par["receive_address"];
            model.receive_mobile = par["receive_mobile"];
            model.receive_name = par["receive_name"];
            model.receive_zip = par["receive_zip"];
            model.seller_actions = par["seller_actions"];
            model.seller_email = par["seller_email"];
            model.seller_id = par["seller_id"];
            model.sign = par["sign"];
            model.sign_type = par["sign_type"];
            model.subject = par["subject"];
            model.total_fee = par["total_fee"];
            model.trade_no = par["trade_no"];
            model.trade_status = par["trade_status"];
            model.use_coupon = par["use_coupon"];
            model.request_page = this.Page.GetType().Name;
            new Bll.EventForSuunto.BLLSuunto_Paylog().SuuntoPaylogInsert(sqlCon, model);
        }

        public string GetGender(object obj)
        {
            if (obj.ToString() == "男")
                return "先生";
            else
                return "女士";

        }
    }
}
